package com.dpj.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j(topic = "c.TestCyclicBarrier")
public class TestCyclicBarrier {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        CyclicBarrier cyclicBarrier=new CyclicBarrier(2,()->{
            log.debug("task1,task2 finished");
        });

        for (int i = 0; i <= 2 ; i++) {
            pool.submit(()->{
                log.debug("task1 begin");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    cyclicBarrier.await(); //计数减1 ,线程都阻塞在这里，只有当计算等于0时，线程才会继续向下运行
                    log.debug("task1 end");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
            pool.submit(()->{
                log.debug("task2 begin");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    cyclicBarrier.await(); //计数减1 ,线程都阻塞在这里，只有当计算等于0时，线程才会继续向下运行
                    log.debug("task2 end");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }


        pool.shutdown();
    }
}
